package com.weixin.program.cron;

import com.weixin.program.config.WeixinProperties;
import com.weixin.program.po.Record;
import com.weixin.program.ro.UserData;
import com.weixin.program.service.RecordService;
import com.weixin.program.utils.EmailUtil;
import com.weixin.program.utils.ExcelUtil;
import com.weixin.program.utils.WeixinUtil;
import com.weixin.program.vo.ExcelData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年03⽉04⽇<br/>
 * @version：v1.0.0<br>
 */
@Slf4j
@Component
public class EmailCron {

    @Autowired
    WeixinProperties properties;

    @Autowired
    Environment environment;

    @Autowired
    RecordService recordService;


    /**
     * 每周五18:30发送本周统计数据;每个月月末最后一天发送当月统计数据
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 30 18 * * ?")
    public void sendEmail() throws Exception {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 获取当天日期为周几
        DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
        int value = dayOfWeek.getValue();
        // 获取本月最后一天
        LocalDateTime date = LocalDateTime.now();
        LocalDateTime lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
        String lastDate = lastDay.format(fmt);
        // 获取当天日期
        String currentDate = date.format(fmt);
        // 判断是否为本月最后一天
        if (lastDate.equals(currentDate)) {
            LocalDateTime startTime = date.with(TemporalAdjusters.firstDayOfMonth());
            String startDate = startTime.format(fmt);
            String touserid = properties.getTouserid();
            process("本月考勤统计", startDate, currentDate, touserid);
        } else {
            // 判断是否周五
            if (value == DayOfWeek.FRIDAY.getValue()) {
                LocalDate localDate = LocalDate.now();
                LocalDate start = localDate.with(WeekFields.of(Locale.CHINA).dayOfWeek(), 2L);
                String startDate = start.format(fmt);
                LocalDate end = localDate.with(WeekFields.of(Locale.CHINA).dayOfWeek(), 7L);
                String endDate = end.format(fmt);
                String touserid = properties.getTouserid();
                process("本周考勤统计", startDate, endDate, touserid);
            }
        }
    }

    /**
     * 发送Excel请求
     *
     * @param sheetName
     * @param startDate
     * @param endDate
     * @param touserid
     */
    public void process(String sheetName, String startDate, String endDate, String touserid) throws Exception {
        String token = WeixinUtil.getToken(properties.getAppid(), properties.getAppsecret());
        UserData userData = WeixinUtil.getUserData(touserid, token);
        String nickName = userData.getNickName();
        String gender = userData.getSex() == 1 ? "先生" : "女士";
        List<Record> records = recordService.selectInSectionTime(startDate, endDate, touserid);
        List<ExcelData> excelDatas = new ArrayList<>(records.size());
        records.stream().forEach(record -> {
            ExcelData excelData = new ExcelData();
            BeanUtils.copyProperties(record, excelData);
            excelData.setNickName(nickName);
            String status = record.getStatus() == 1 ? "已打卡" : "未打卡";
            excelData.setStatus(status);
            excelDatas.add(excelData);
        });
        String emailId = properties.getEmailId();
        String excelpath = properties.getExcelpath();
        String imagepath = properties.getImagepath();
        ExcelUtil.write(sheetName, excelDatas, ExcelData.class, excelpath, imagepath);
        EmailUtil.sendEmail(emailId, nickName, gender, excelpath, sheetName, imagepath);
    }

}
